class Compiler {
  constructor(vm) {
    this.el = vm.$el
    this.vm = vm
    this.compile(this.el)
  }

  // 编译模板，处理文本节点和元素节点
  compile(el) {
    const childNodes = el.childNodes
    Array.from(childNodes).forEach(node => {
      if(this.isTextNode(node)) {
        this.compileText(node)
      }
      if(this.isElementNode(node)) {
        this.compileElement(node)
      }

      // 递归处理
      if(node.childNodes && node.childNodes.length) {
        this.compile(node)
      }
    })
  }

  // 编译元素节点，处理指令
  compileElement(node) {
    console.dir(node)
    console.dir(node.attributes)
    Array.from(node.attributes).forEach(attr => {
      if(this.isDirective(attr.name)) {
        const attrName = attr.name.substr(2)
        const key = attr.value
        this.update(node, key, attrName)
      }
    })
  }

  update(node, key, attrName) {
    if(attrName.indexOf(':') > 0) {
      const eventName = attrName.substr(3)
      this.onUpdater.call(this, node, key, eventName)
      return
    }
    this[attrName + 'Updater'].call(this, node, this.vm[key], key)
  }

  // 处理v-text指令
  textUpdater(node, val, key) {
    node.textContent = val
    new Watcher(this.vm, key, newVal => node.textContent = newVal)
  }

  // 处理v-model指令
  modelUpdater(node, val, key) {
    node.value = val
    new Watcher(this.vm, key, newVal => node.value = newVal)
    node.addEventListener('input', () => {
      this.vm[key] = node.value
    })
  }

  // 处理v-html指令
  htmlUpdater(node, val, key) {
    node.innerHTML = val
    new Watcher(this.vm, key, newVal => node.innerHTML = newVal)
  }

  // 处理v-on指令
  onUpdater(node, key, eventName) {
    node.addEventListener(eventName, this.vm.$options.methods[key])
  }

  // 编译文本节点，处理差值表达式
  compileText(node) {
    const reg = /\{\{(.+?)\}\}/
    let textContent = node.textContent
    if(reg.test(textContent)) {
      let key = RegExp.$1.trim()
      node.textContent = textContent.replace(reg, this.vm[key])

      new Watcher(this.vm, key, (newVal) => node.textContent = newVal)
    }
  }

  // 判断元素是否是指令
  isDirective(attrName) {
    return attrName.startsWith('v-')
  }

  // 判断节点是否是文本节点
  isTextNode(node) {
    return node.nodeType === 3
  }

  // 判断节点是否是元素节点
  isElementNode(node) {
    return node.nodeType === 1
  }
}